package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartImpl implements ShoppingCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;
    /**
     * 添加购物车
     * @param shoppingCartDTO
     */
    @Override
    public void addCart(ShoppingCartDTO shoppingCartDTO) {
         ShoppingCart cart = new ShoppingCart();
         BeanUtils.copyProperties(shoppingCartDTO,cart);
         cart.setUserId(BaseContext.getCurrentId());
         //条件查询菜品id,套餐id,userId,口味(String)
         List<ShoppingCart> carts= shoppingCartMapper.list(cart);
         //没有就修改数量加一
        if (carts!=null&&carts.size()!=0)
         {
             ShoppingCart shoppingCart=carts.get(0);
             shoppingCart.setNumber(shoppingCart.getNumber()+1);
             shoppingCartMapper.updateNumberById(shoppingCart);
         }else
         {
              Long dishId = shoppingCartDTO.getDishId();
              if (dishId!=null&&dishId!=0)
              {    //说明传过来的是菜品id
                   Dish dish = dishMapper.getById(dishId);
                   cart.setAmount(dish.getPrice());
                   cart.setImage(dish.getImage());
                   cart.setName(dish.getName());
              }else
              {  //说明传过来的是套餐id
                  Setmeal setmeal = setmealMapper.getById(shoppingCartDTO.getSetmealId());
                  cart.setAmount(setmeal.getPrice());
                  cart.setImage(setmeal.getImage());
                  cart.setName(setmeal.getName());
              }
             cart.setNumber(1);
             cart.setCreateTime(LocalDateTime.now());
             shoppingCartMapper.insert(cart);
         }


    }

    /**
     * 查询购物车
     * @return
     */
    @Override
    public List<ShoppingCart> list() {
       ShoppingCart shoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
       List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        return shoppingCarts;
    }

    /**
     * 清除购物车
     */
    @Override
    public void clear() {
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
    }
}
